//
//  HCNewReassignPeopleListViewController.m
//  HCNewGoldFinger
//
//  Created by zjhcsoft on 14-10-13.
//  Copyright (c) 2014年 zjhcsoftios. All rights reserved.
//  转派人员页面

#import "ZPHCNewReassignPeopleListViewController.h"
#import "ZSBContactAreaMenu.h"
#import "ZSBContactInfo.h"
#import "ZSBContactInfoCell.h"
#import "ZSBReadJsonDate.h"
#import "HCNewReAssignSearchResultViewController.h"
#import "SendWorkOrderAndUploadImageController.h"
#import "UIColor+EX.h"
#import "NetworkAddress.h"
#import "SVProgressHUD.h"
#import "iSeeNetworkRequest.h"

@interface ZPHCNewReassignPeopleListViewController ()<ZSBContactAreaMenuDelegate>

@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, strong) ZSBContactAreaMenu *menu; //区域菜单

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dateTree; //数据源

@property (nonatomic, strong) NSMutableArray *dateList; //数据源

@property (nonatomic, assign) NSInteger rowsForTableView; //列表行数

@property (nonatomic, assign) NSInteger selectIndex; //当前区域

@property (nonatomic, assign) ZSBContactInfo *currentContactInfo; //当前操作节点

@property (nonatomic, strong) NSNumber * userRowId;

@property (nonatomic, strong) NSString *redirectBz;

@end

@implementation ZPHCNewReassignPeopleListViewController
{
    NSMutableArray *messageList;
}
- (NSMutableArray *)dateTree
{
    if (_dateTree == nil) {
        _dateTree = [[NSMutableArray alloc] init];
    }
    return _dateTree;
}
- (NSMutableArray *)dateList
{
    if (_dateList == nil) {
        _dateList = [[NSMutableArray alloc] init];
    }
    return _dateList;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.view.backgroundColor = [UIColor colorWithHexString:@"EFEFF4"];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(100, 20, 120, 44)];
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.text = @"联系人";
        titleLab.font = [UIFont systemFontOfSize:18];
        titleLab.backgroundColor = [UIColor clearColor];
        titleLab.textColor = [UIColor whiteColor];
        self.navigationItem.titleView = titleLab;

        
        UIButton *leftBtnView = [UIButton buttonWithType:UIButtonTypeCustom];
        leftBtnView.tag = 1;
        leftBtnView.frame = CGRectMake(0, 0, 28, 28);
        [leftBtnView setImage:[UIImage imageNamed:@"toolbar_btn_back"] forState:UIControlStateNormal];
        [leftBtnView addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithCustomView:leftBtnView];
        self.navigationItem.leftBarButtonItem = leftBtn;
        
        _dateTree = [[NSMutableArray alloc] init];
        _dateList = [[NSMutableArray alloc] init];
        messageList = [[NSMutableArray alloc] init];
    }
    return self;
}

- (instancetype)initWithIsPZ:(BOOL ) isPD {
    self = [super init];
    if (self) {
        _isPD = isPD;
        self.view.backgroundColor = [UIColor colorWithHexString:@"EFEFF4"];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(100, 20, 120, 44)];
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.text = @"联系人";
        titleLab.font = [UIFont systemFontOfSize:18];
        titleLab.backgroundColor = [UIColor clearColor];
        titleLab.textColor = [UIColor whiteColor];
        self.navigationItem.titleView = titleLab;
        
        UIButton *leftBtnView = [UIButton buttonWithType:UIButtonTypeCustom];
        leftBtnView.tag = 1;
        leftBtnView.frame = CGRectMake(0, 0, 28, 28);
        [leftBtnView setImage:[UIImage imageNamed:@"toolbar_btn_back"] forState:UIControlStateNormal];
        [leftBtnView addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithCustomView:leftBtnView];
        self.navigationItem.leftBarButtonItem = leftBtn;
        _dateTree = [[NSMutableArray alloc] init];
        _dateList = [[NSMutableArray alloc] init];
        messageList = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.frame = CGRectMake(0, 0, kScreenWidth, 50);
    _searchBar.placeholder = @"搜索";
    _searchBar.delegate = self;
    _searchBar.barStyle = UIBarStyleDefault;
    [self.view addSubview:_searchBar];
    
    UIView *inputAccView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    inputAccView.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"完成" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    button.frame = CGRectMake(self.view.frame.size.width-60, 0, 60, 40);
    [button addTarget:self action:@selector(searchBarDidEndSelect:) forControlEvents:UIControlEventTouchUpInside];
    [inputAccView addSubview:button];
    
    _searchBar.inputAccessoryView = inputAccView;
    
    _tableView  = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.autoresizingMask = UIViewAutoresizingNone;
    _tableView.backgroundView = nil;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self getChangeCompList];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)back:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)goBackToListView
{
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"MY_WORKORDER_REFRESH_LIST" object:nil];
    NSArray * array = self.navigationController.viewControllers;
    for (NSUInteger i = array.count-1; i >= 0; i--)
    {
        UIViewController *ctrl = array[i];
        if ([ctrl isKindOfClass:NSClassFromString(@"ZSBWorkOrderViewController")] || [ctrl isKindOfClass:NSClassFromString(@"ZSBWorkOrderListViewController")] || [ctrl isKindOfClass:NSClassFromString(@"NewMissonListController")]) {
            [self.navigationController popToViewController:ctrl animated:YES];
            break;
        }
    }

    
}
//获取以当前用户本级节点，本地网节点，常用联系人列表

- (void)getChangeCompList
{
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    if (_isPD) {
        [parmas setObject:@"pd" forKey:@"sendOrBatch"];
    }
    [SVProgressHUD show];
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPChangeCompList) params:parmas success:^(id object) {
        if ([object[@"code"] integerValue] == 200) {
            if (self.currentContactInfo == nil) {
                [self.dateTree addObjectsFromArray:[ZSBReadJsonDate readJSonStringContactAreaList:[self DataTOjsonString:object] andLevel:-1]];
                
                NSInteger myIndex = 0;
                NSNumber *myCompanyID = [ZSBReadJsonDate readJSonStringContactInfoListMyCompanyID:[self DataTOjsonString:object]];
                for (ZSBContactInfo *info in self.dateTree) {
                    if ([info.sysCompanyRowId integerValue] == [myCompanyID integerValue]) {
                        myIndex = [self.dateTree indexOfObject:info];
                        break;
                    }
                }
                //                _menu.myIndex = myIndex;
                //                _menu.dateList = _dateTree;
                self.tableView.frame = CGRectMake(0, 50, kScreenWidth, kScreenHeight - Height_NavBar - 50);
                
                ZSBContactInfo *contactInfo = [self.dateTree objectAtIndex:myIndex];
                self.currentContactInfo = contactInfo;
                self.selectIndex = myIndex;
                
                [self.currentContactInfo.subContactInfoList addObjectsFromArray:[ZSBReadJsonDate readJSonStringContactInfoList:[self DataTOjsonString:object] andLevel:self.currentContactInfo.level+1]];
                
                [self rowsForTableView:[self.dateTree objectAtIndex:self.selectIndex]];
                
                [self.tableView reloadData];
            }
        }
        [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
    
    
    
}
//获取单位结点下的组织或用户

- (void)getList:(NSNumber *)sysCompanyRowId
{
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    if ([sysCompanyRowId boolValue]) {
        [parmas setValue:sysCompanyRowId forKey:@"sysCompanyRowId"];
    }
    [SVProgressHUD show];
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPChangeUserList) params:parmas success:^(id object) {
        [SVProgressHUD dismiss];
        self.currentContactInfo.isExpansion = YES;
        [self.currentContactInfo.subContactInfoList addObjectsFromArray:[ZSBReadJsonDate readJSonStringContactInfoList:[self DataTOjsonString:object] andLevel:self.currentContactInfo.level+1]];
        
        [self.dateList removeAllObjects];
        [self rowsForTableView:[self.dateTree objectAtIndex:self.selectIndex]];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
    
}

- (void)searchForNet:(NSString *)userSelectStr
{
    
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    if (userSelectStr) {
        [parmas setValue:userSelectStr forKey:@"userSelectStr"];
    }
    [SVProgressHUD showWithStatus:@"正在搜索数据..."];
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@", NMarketMainUrl,ZPgetUserListBySearch) params:parmas success:^(id object) {
        [SVProgressHUD dismiss];
        NSArray *array = [ZSBReadJsonDate readJSonStringContactInfoList:[self DataTOjsonString:object] andLevel:0];
        NSLog(@"%@",array);
        if (array.count == 0) {
            [SVProgressHUD showErrorWithStatus:@"没有结果"];
        }else{
            HCNewReAssignSearchResultViewController *viewCtrl = [[HCNewReAssignSearchResultViewController alloc] init];
            viewCtrl.titleName = [NSString stringWithFormat:@"搜索条件:(%@)",self.searchBar.text];
            viewCtrl.dateList = array;
            viewCtrl.billIds = self.billIds;
            viewCtrl.zpRemarkFlag = self.zpRemarkFlag;
            viewCtrl.zpHdImageFlag = self.zpHdImageFlag;
            viewCtrl.isPD = self.isPD;
            viewCtrl.isReceiveAndTransfer = self.isReceiveAndTransfer;
            [self.navigationController pushViewController:viewCtrl animated:YES];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
    
}


#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dateList.count;
}
#pragma mark -
#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZSBContactInfo *contactInfo = [_dateList objectAtIndex:indexPath.row];
    if (contactInfo.contactType == ZSBContactTypeCompany) {
        return 44;
    }else{
        return 60;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellName = @"ZSBCommentaryCell";
    ZSBContactInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (cell == nil) {
        cell = [[ZSBContactInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
    }
    ZSBContactInfo *contactInfo = [_dateList objectAtIndex:indexPath.row];
    cell.contactInfo = contactInfo;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ZSBContactInfo *contactInfo = [_dateList objectAtIndex:indexPath.row];
    if (contactInfo.contactType == ZSBContactTypeCompany) {
        self.currentContactInfo = contactInfo;
        if (contactInfo.isExpansion == YES) {
            contactInfo.isExpansion = NO;
            [_dateList removeAllObjects];
            
            [self rowsForTableView:[_dateTree objectAtIndex:self.selectIndex]];
        }else{
            if (contactInfo.subContactInfoList.count == 0) {
                [self getList:contactInfo.sysCompanyRowId];
            }else{
                contactInfo.isExpansion = YES;
                [_dateList removeAllObjects];
                [self rowsForTableView:[_dateTree objectAtIndex:self.selectIndex]];
            }
        }
        [_tableView reloadData];
    }
    else if (contactInfo.contactType == ZSBContactTypeUser)
    {
        self.userRowId = contactInfo.sysUserRowId;
        
        
        //派单或者转派
        if (_isPD) {
            
            [self paidan];
            
        }else {

            SendWorkOrderAndUploadImageController *abc = [[SendWorkOrderAndUploadImageController alloc] init];
            abc.tpye = 1;
            abc.billIds = self.billIds;
            abc.userRowId = self.userRowId;
            abc.zpRemarkFlag = self.zpRemarkFlag;
            abc.zpHdImageFlag = self.zpHdImageFlag;
            abc.shaidan = self.shaidan;
            abc.isReceiveAndTransfer = self.isReceiveAndTransfer;
            [self.navigationController pushViewController:abc animated:YES];

        }
        
        
        
    }
}

- (void)rowsForTableView:(ZSBContactInfo *)contactInfo
{
    if (contactInfo.subContactInfoList.count>0) {
        for (ZSBContactInfo *subContactInfo in contactInfo.subContactInfoList) {
            if (contactInfo.isExpansion == YES) {
                [_dateList addObject:subContactInfo];
                [self rowsForTableView:subContactInfo];
            } 
        }
    }
}

#pragma mark -
#pragma mark Download support (ZSBContactAreaMenuDelegate)

- (void)menuDidSelectWithInfo:(ZSBContactInfo *)contactInfo andIndex:(NSInteger)index
{
    if (_dateList.count>0) {
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:NO];
    }
    self.currentContactInfo = [_dateTree objectAtIndex:index];
    self.selectIndex = index;
    if (self.currentContactInfo.subContactInfoList.count>0) {
        [_dateList removeAllObjects];
        [self rowsForTableView:[_dateTree objectAtIndex:self.selectIndex]];
        [_tableView reloadData];
    }else{
        [self getList:contactInfo.sysCompanyRowId];
    }
}
#pragma mark -
#pragma mark Download support (UISearchBarDelegate)

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [_searchBar resignFirstResponder];
    if (searchBar.text.length>0) {
      [self searchForNet:searchBar.text];
        

    }
    
}



- (void)searchBarDidEndSelect:(UIButton *)button
{
    [_searchBar resignFirstResponder];
}

#pragma mark 派单

- (void)paidan {
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:self.billIds forKey:@"orderIds"];
    [parmas setObject:self.userRowId forKey:@"pgUserId"];
    
    [SVProgressHUD showWithStatus:@"派单中"];
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPpaidan) params:parmas success:^(id object) {
        [SVProgressHUD showSuccessWithStatus:@"派单成功"];
        [self performSelector:@selector(goBackToListView) withObject:nil afterDelay:0];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"派单失败"];
    }];

}

-(NSString*)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else { 
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
    } 
    return jsonString; 
}


@end
